<template>
  <el-dialog
    :title="$t('m.OPERATOR_DETAILS')"
    custom-class="operator-dialog"
    :close-on-click-modal="false"
    :modal="false"
    :visible.sync="open"
    :before-close="handleClose"
  >
    <el-scrollbar class="operator-scrollbar" wrap-class="operator-scrollbar__wrap">
      <el-form
        ref="form"
        :class="readonly ? 'detail' :'edit'"
        label-suffix=":"
        inline
        size="small"
        :rules="rules"
        :model="formData"
        hide-required-asterisk
      >
        <div class="row">
          <el-form-item :label="$t('m.LOGIN_NAME')" prop="userName">
            <el-input v-model="formData.userName" :readonly="readonly"></el-input>
          </el-form-item>
        </div>
        <div class="row">
          <el-form-item :label="$t('m.PASSWORD')" prop="userPwd">
            <el-input type="password" v-model="formData.userPwd" :readonly="readonly"></el-input>
          </el-form-item>
        </div>
        <el-row class="row">
          <el-col :span="12">
            <el-form-item :label="$t('m.REAL_NAME')" prop="realName">
              <el-input v-model="formData.realName" :readonly="readonly"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('m.PRIORITY')" prop="priorityLevel">
              <el-input
                oninput="value=value.replace(/[^\d]/g,'')"
                :placeholder="$t('m.tip.PRIORITY_1_255')"
                v-model="formData.priorityLevel"
                :readonly="readonly"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="row">
          <el-col :span="12">
            <el-form-item :label="$t('m.OPERATOR_TYPES')" prop="userType">
              <el-select
                v-model="formData.userType"
                popper-class="default-select-popper"
                :disabled="disabled"
              >
                <el-option
                  v-for="opt in operatorTypeOption"
                  :key="opt.value"
                  :label="$t('m.dict.operatorType')[opt.value]"
                  :value="opt.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('m.LOGIN_TYPE')" prop="loginType">
              <!-- 暂时写死 -->
              <el-input :value="$t('m.UNIFIED_IDENTITY_AUTHENTICATION')" disabled></el-input>
              <!-- <el-select
                    v-model="formData.loginType"
                    popper-class="default-select-popper"
                    :disabled="disabled"
                  >
                    <el-option
                      v-for="opt in loginTypeOption"
                      :key="opt.value"
                      :label="opt.label"
                      :value="opt.value"
                    ></el-option>
              </el-select>-->
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="row">
          <el-col :span="12">
            <el-form-item :label="$t('m.LEFT_HANDLE')" prop="mainTel">
              <el-input v-model="formData.mainTel" :readonly="readonly"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('m.RIGHT_HANDLE')" prop="viceTel">
              <el-input v-model="formData.viceTel" :readonly="readonly"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="row">
          <el-col :span="12">
            <el-form-item :label="$t('m.LEFT_HANDLE_TYPE')" prop="mainTelType">
              <el-select
                v-model="formData.mainTelType"
                popper-class="default-select-popper"
                :disabled="disabled"
              >
                <el-option
                  v-for="opt in phoneTypeOption"
                  :key="opt.value"
                  :label="$t('m.dict.deviceTypeOptions')[opt.value]"
                  :value="opt.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('m.RIGHT_HANDLE_TYPE')" prop="viceTelType">
              <el-select
                v-model="formData.viceTelType"
                popper-class="default-select-popper"
                :disabled="disabled"
              >
                <el-option
                  v-for="opt in phoneTypeOption"
                  :key="opt.value"
                  :label="$t('m.dict.deviceTypeOptions')[opt.value]"
                  :value="opt.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item :label="$t('m.PERMISSION_GROUP')" prop="rightGroupID">
              <el-select
                v-model="formData.rightGroupID"
                popper-class="default-select-popper"
                :disabled="disabled"
              >
                <el-option
                  v-for="opt in authListOption"
                  :key="opt.rightGroupID"
                  :label="opt.rightGroupName"
                  :value="opt.rightGroupID"
                ></el-option>
              </el-select>
              <!-- <el-input :value="formData.rightGroupName" disabled></el-input> -->
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('m.DISPATCH_GROUP')" prop="groupID">
              <el-input :value="getGroupName(formData)" disabled></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-show="false">
          <el-col :span="12">
            <el-form-item :label="$t('m.SMS_GATEWAY')" prop="mobile">
              <el-input v-model="formData.mobile" :readonly="readonly"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('m.KEY_ID')" prop="softKey">
              <el-input v-model="formData.softKey" :readonly="readonly"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="row" v-show="false">
          <el-col :span="12">
            <el-form-item :label="$t('m.GPS_NUMBER')" prop="gpsBH">
              <el-input v-model="formData.gpsBH" :readonly="readonly"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('m.PHONE_AUTHENTICATION')" prop="telphone">
              <el-input v-model="formData.telphone" :readonly="readonly"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="row">
          <el-form-item :label="$t('m.DUTY_MODE')" prop>
            <el-switch
              :disabled="readonly"
              v-model="formData.onDuty"
              active-color="#13ce66"
              inactive-color="#ff4949"
              :active-text="$t('m.ON')"
              :inactive-text="$t('m.OFF')"
              active-value="true"
              inactive-value="false"
            ></el-switch>
          </el-form-item>
        </div>
        <div class="row" v-show="false">
          <el-form-item :label="$t('m.CLUSTER_MONITRING')" prop>
            <el-switch
              :disabled="readonly"
              v-model="formData.monitor"
              active-color="#13ce66"
              inactive-color="#ff4949"
              :active-text="$t('m.ON')"
              :inactive-text="$t('m.OFF')"
              active-value="1"
              inactive-value="0"
            ></el-switch>
          </el-form-item>
        </div>
        <el-form-item :label="$t('m.CAMERA')" prop="videoID" class="form-item-group" v-show="false">
          <div class="group-item" v-for="(item, index) in formData.videoID" :key="item">
            <svg-icon
              icon-class="remove"
              v-if="!readonly"
              @click="removeList(formData.videoID, item, index, 'videoTree')"
            ></svg-icon>
            <el-input :value="getVideoName(item)" readonly></el-input>
          </div>
          <div class="group-item add" v-if="!readonly">
            <svg-icon icon-class="plus" @click="addVideo()"></svg-icon>
            <label class="add-label" @click="addVideo()">{{$t('m.ADD_CAMERA')}}</label>
          </div>
        </el-form-item>
        <div class="remark">
          <el-form-item :label="$t('m.REAMRKS')" prop="remark">
            <el-input type="textarea" :rows="3" v-model="formData.remark" :readonly="readonly"></el-input>
          </el-form-item>
        </div>
      </el-form>
    </el-scrollbar>
    <div slot="footer" class="dialog-footer">
      <el-button
        @click="handleEdit(submitBtn)"
        :disabled="commitDisabled"
        size="small"
      >{{ submitBtn ? $t('m.CONFIRM') : $t('m.EDIT') }}</el-button>
      <el-button @click="handleClose" size="small">{{$t('m.CANCEL')}}</el-button>
    </div>
    <!-- 组选择 -->
    <div class="default-select-tree groupTree" v-show="showTree === 'groupTree'">
      <el-scrollbar class="tree-scrollbar" wrap-class="tree-scrollbar__wrap">
        <el-tree
          :data="userGroupTreeData"
          icon-class="el-icon-arrow-right"
          node-key="nid"
          highlight-current
          @check-change="groupCheckChange"
          :filter-node-method="groupFilter"
          show-checkbox
          check-strictly
          ref="groupTree"
        ></el-tree>
      </el-scrollbar>
    </div>
    <!-- 摄像头选择 -->
    <div class="default-select-tree videoTree" v-show="showTree === 'videoTree'">
      <el-scrollbar class="tree-scrollbar" wrap-class="tree-scrollbar__wrap">
        <el-tree
          :data="videoTreeData"
          class="is-leaf-checkbox"
          icon-class="el-icon-arrow-right"
          node-key="nid"
          highlight-current
          @check-change="videoCheckChange"
          show-checkbox
          :props="videoProps"
          check-strictly
          ref="videoTree"
        ></el-tree>
      </el-scrollbar>
    </div>
  </el-dialog>
</template>

<script>
import { dataflow } from '@/api/data'
import { mapGetters } from 'vuex'
import { rightgroup } from '@/api/dataManage'
export default {
  props: {
    open: Boolean,
    title: String,
    formData: Object,
    editFlag: Boolean, //进入时判断是否直接编辑页面标识
  },

  computed: {
    ...mapGetters([
      'dict',
      'groupMap',
      'videoMap',
      'videoTreeData',
      'userGroupTreeData',
      'videoNidMap',
    ]),

    rules() {
      return {
        userName: [
          {
            required: true,
            // message: '登录名不能为空',
            message: this.$t('m.tip.CAN_NOT_BE_EMPTY'),
            trigger: 'blur',
          },
        ],
        // telphone: [
        //   {
        //     required: true,
        //     message: '手机验证不能为空',
        //     trigger: 'blur',
        //   },
        // ],
        priorityLevel: [
          {
            required: true,
            // message: '优先级不能为空',
            message: this.$t('m.tip.CAN_NOT_BE_EMPTY'),
            trigger: 'blur',
          },
        ],
        realName: [
          {
            required: true,
            // message: '姓名不能为空',
            message: this.$t('m.tip.CAN_NOT_BE_EMPTY'),
            trigger: 'blur',
          },
        ],
        userPwd: [
          {
            required: true,
            // message: '密码不能为空',
            message: this.$t('m.tip.CAN_NOT_BE_EMPTY'),
            trigger: 'blur',
          },
        ],
        mainTel: [
          {
            required: true,
            // message: '左手柄不能为空',
            message: this.$t('m.tip.CAN_NOT_BE_EMPTY'),
            trigger: 'blur',
          },
        ],
        rightGroupID: [
          {
            required: true,
            // message: '权限组不能为空',
            message: this.$t('m.tip.CAN_NOT_BE_EMPTY'),
            trigger: 'blur',
          },
        ],
        groupID: [
          {
            required: true,
            // message: '所属组不能为空',
            message: this.$t('m.tip.CAN_NOT_BE_EMPTY'),
            trigger: 'blur',
          },
        ],
      }
    },
  },
  data() {
    return {
      defaultImg: require('@/assets/images/add-picture.png'),
      readonly: true, // 详情时只读
      disabled: true,
      submitBtn: false,
      checkedPerson: [],
      videoProps: {
        disabled: (data, node) => {
          node.isLeaf = data.children ? false : true
          return !node.isLeaf
        },
      },
      dutyProps: {
        label: 'dutyName',
      },
      uploadHeaders: {
        ContentType: 'multipart/form-data',
        Authorization: sessionStorage.getItem('tokenSign'),
      },
      actionUrl: '/materials/person/imgUpload',
      acceptType: 'image/*', //图片格式
      groupValid: '', // 组校验信息
      telValid: '',
      commitDisabled: false, // 提交按钮
      dutyData: [
        {
          dutyID: '1',
          dutyName: '总经理',
        },
        {
          dutyID: '2',
          dutyName: '副总经理',
        },
        {
          dutyID: '3',
          dutyName: '科长',
        },
        {
          dutyID: '4',
          dutyName: 'test',
        },
      ], // 职务数据
      phoneTypeOption: [
        {
          value: 'phone',
          label: '话机',
        },
        {
          value: 'hand_microphone',
          label: '手咪',
        },
      ],
      operatorTypeOption: [
        {
          value: 'operator',
          label: '普通坐席',
        },
        {
          value: 'monitor',
          label: '班长坐席',
        },
      ],
      loginTypeOption: [
        {
          value: 'normal',
          label: '密码身份认证',
        },
        {
          value: 'banzhang',
          label: '统一身份认证',
        },
      ],
      showTree: '',
      groupOption: [],
      dutyOption: [],
      authListOption: [],
    }
  },
  watch: {
    'formData.group'(newValue) {
      if (newValue.length > 0) {
        this.groupValid = ''
      }
    },
    'formData.device'(newValue) {
      if (newValue.length === 0) {
        this.formData.defaultNo = ''
      } else if (newValue.length === 1 && newValue[0].deviceTel) {
        this.formData.defaultNo = newValue[0].deviceTel
      }
    },
  },
  methods: {
    // 文件上传成功
    onSuccess(response, file) {
      console.log('onSuccess', response)
      let URL
      if (window.createObjectURL != undefined) {
        // basic
        URL = window.createObjectURL(file.raw)
      } else if (window.URL != undefined) {
        // mozilla(firefox)
        URL = window.URL.createObjectURL(file.raw)
      } else if (window.webkitURL != undefined) {
        // webkit or chrome
        URL = window.webkitURL.createObjectURL(file.raw)
      }
      this.formData.localUrl = URL
      this.formData.ico = response.true
    },
    // 组选择框改变
    groupCheckChange(node, checked) {
      if (checked) {
        if (!this.formData.group.some((g) => g.groupID === node.obj.groupID)) {
          this.formData.group.push({
            groupID: node.obj.groupID,
            groupName: node.obj.groupName,
          })
        }
      } else {
        let index = this.formData.group.findIndex(
          (g) => g.groupID === node.obj.groupID
        )
        if (idnex !== -1) this.formData.group.splice(index, 1)
      }
    },
    // 职员选择框改变
    dutyCheckChange(node, checked) {
      if (checked) {
        if (!this.formData.dutyName.some((name) => name === node.dutyName)) {
          this.formData.dutyName.push(node.dutyName)
        }
      } else {
        let index = this.formData.dutyName.findIndex(
          (item) => item === node.dutyName
        )
        if (idnex !== -1) this.formData.dutyName.splice(index, 1)
      }
    },
    // 摄像头选择框改变
    videoCheckChange(node, checked) {
      if (this.formData.videoID == undefined) {
        this.formData.videoID = []
      }
      if (checked) {
        if (
          !this.formData.videoID.some((videoID) => videoID === node.obj.videoID)
        ) {
          this.formData.videoID.push(node.obj.videoID)
        }
      } else {
        let index = this.formData.videoID.findIndex(
          (videoID) => videoID === node.obj.videoID
        )
        if (idnex !== -1) this.formData.videoID.splice(index, 1)
      }
    },
    // 组过滤
    groupFilter(value, data, node) {
      return data.obj.groupType !== 'dispatchgroup'
    },
    // 添加组按钮
    addGroup() {
      this.showTree = 'groupTree'
      this.$nextTick(() => {
        this.$refs.groupTree.filter()
        this.formData.group.forEach((item) => {
          let node = this.groupMap.get(item.groupID)
          if (node) {
            this.$refs.groupTree.setChecked(node.nid, true)
          }
        })
      })
    },
    // 添加职务按钮
    addDuty() {
      this.showTree = 'dutyTree'
      this.$nextTick(() => {
        this.formData.dutyName.forEach((name) => {
          let duty = this.dutyData.find((item) => item.dutyName === name)
          if (duty) {
            this.$refs.dutyTree.setChecked(duty.dutyID, true)
          }
        })
      })
    },
    // 添加号码按钮
    addTel() {
      const length = this.formData.device.length
      this.formData.device.push({
        deviceTel: '',
        orderNO: length + 1,
        deviceType: 'office',
      })
    },
    // 添加摄像头按钮
    addVideo() {
      this.showTree = 'videoTree'
      this.$nextTick(() => {
        this.formData.videoID.forEach((videoID) => {
          let nids = this.videoNidMap.get(videoID)
          if (nids) {
            this.$refs.videoTree.setChecked(nids[0], true)
          }
        })
      })
    },
    // 获取组名称
    getGroupName(item) {
      let group = this.groupMap.get(item.groupID)
      if (group) item.groupName = group.obj.groupName
      return item.groupName || ''
    },
    // 获取摄像头名称
    getVideoName(videoID) {
      let video = this.videoMap.get(videoID)
      // if (video) item.groupName = group.obj.groupName;
      return video ? video.videoName : ''
    },
    // 删除按钮
    removeList(list, id, index, treeRef) {
      list.splice(index, 1)
      this.$nextTick(() => {
        switch (treeRef) {
          case 'videoTree':
            let nids = this.videoNidMap.get(id)
            if (nids) {
              this.$refs[treeRef].setChecked(nids[0], false)
            }
            break
          case 'groupTree':
            let node = this.groupMap.get(id)
            if (node) {
              this.$refs[treeRef].setChecked(node.nid, false)
            }
            break
          case 'dutyTree':
            let duty = this.dutyData.find((item) => item.dutyName === id)
            if (duty) {
              this.$refs[treeRef].setChecked(duty.dutyID, false)
            }
            break
          case 'tel':
            if (list.length === 0) this.formData.defaultNo = ''
            else if (list.length === 1 && list[0].deviceTel)
              this.formData.defaultNo = list[0].deviceTel
            break
        }
      })
    },
    // 按钮是否禁用
    toolBtnDistabled() {
      if (this.formData.type === 'label') {
        return this.formData.personList.length > 0
      }
      return false
    },
    //编辑
    handleEdit(submitBtn) {
      if (!submitBtn) {
        this.readonly = false
        this.disabled = false
        this.submitBtn = true
      } else {
        let form = this.formData
        this.commitDisabled = true
        this.$refs['form'].validate((valid) => {
          if (valid) {
            // console.log('handleEdit', JSON.stringify(form))
            // 提交表单
            if (form.operatorID) {
              //修改
              SDK.operatorMod(form)
                .then((res) => {
                  this.handleClose()
                  this.$store.dispatch('initUser')
                  this.$emit('clearTableData')
                })
                .catch((err) => {
                  console.log(err)
                  this.commitDisabled = false
                })
            } else {
              //新增
              this.handleCreate()
            }
          } else {
            this.commitDisabled = false
          }
        })
      }
    },
    //新建
    handleCreate() {
      let form = this.formData
      form['@id'] = '100000'
      form['@type'] = 'OperatorAdd'
      form['pos_x'] = ''
      form['pos_y'] = ''
      form['loginType'] = 'normal'
      form['iocType'] = ''
      form['faxTel'] = ''
      form['dutyTel'] = ''
      form['videoID'] = []
      let obj = {
        request: form,
      }
      dataflow(obj).then((res) => {
        if (res.status == 200) {
          this.handleClose()
          this.$store.dispatch('initUser')
          this.$emit('clearTableData')
        }
      })
    },
    // 关闭或取消
    handleClose() {
      this.$emit('update:open', false)
    },
    // 监听鼠标事件
    clickEvent(e) {
      var box = document.getElementsByClassName(
        `default-select-tree ${this.showTree}`
      )[0]
      if (box && !box.contains(e.target)) {
        this.showTree = ''
      }
    },
    //添加电话按钮
    addTel() {
      this.formData.device.push({
        deviceType: '',
        deviceTel: '',
      })
    },
    //添加职务按钮
    addDuty() {
      this.formData.dutyName.push('')
    },
    change(e) {
      this.$forceUpdate()
    },
    getGroupOption() {
      let _this = this
      this.groupOption = []
      this.groupMap.forEach((e) => {
        // console.log(e.parentID)
        if (e.parentID == null || e.parentID == '') {
          _this.groupOption.push(e)
        }
      })
    },
    //获取权限组
    getAuthGroup() {
      let obj = {
        event: 'QueryRightGroup',
      }
      rightgroup(obj).then((res) => {
        let authListOption = res.data.eventdata
        this.authListOption = authListOption.filter((e) => {
          return e.isAdmin == 0
        })
      })
    },
  },
  mounted() {
    this.getGroupOption()
    this.getAuthGroup()
    this.$nextTick(() => {
      document.addEventListener('click', this.clickEvent, true)
      //判断是否直接进如编辑或详情页
      if (this.editFlag) {
        this.handleEdit(!this.editFlag)
      }
    })
  },
  destroyed() {
    document.removeEventListener('click', this.clickEvent, true)
  },
}
</script>

<style lang="scss" scoped>
@import '~@/assets/scss/operator_dialog.scss';
</style>
